package com.pro.common.modules.service.dependencies.upload;


import cn.hutool.core.util.IdUtil;
import com.pro.common.api.enums.EnumSysRole;
import com.pro.framework.api.FrameworkConst;
import com.pro.framework.api.util.LogicUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Component
public class FileUploadService {
    public static FileUploadService INSTANCE;

    //    private final MinioClient minioClient;
    // 项目
    private final String bucket;
    private final String springApplicationName;
    private final MinioProperties minioProperties;

    public FileUploadService(MinioProperties minioProperties,
                             @Value("${spring.application.name}") String springApplicationName) {
//        this.minioClient = MinioClient.builder()
//                .endpoint(minioProperties.getEndpoint())
//                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
//                .build();
        this.minioProperties = minioProperties;
        this.bucket = minioProperties.getBucket();
        this.springApplicationName = springApplicationName;
        INSTANCE = this;
    }

//    /**
//     * minio:
//     * endpoint: http://localhost:9000
//     * accessKey: admin
//     * secretKey: password
//     * bucket: user/agent 等项目/服务/子目录
//     * 上传
//     */
//    public String uploadFile(EnumSysRole sysRole, MultipartFile file, String subModule) {
//        return uploadFile(sysRole, file, springApplicationName, subModule);
//    }

    public String uploadFile(EnumSysRole sysRole, MultipartFile file, String module, String subModule, Boolean oriNameFlag) {
        if (oriNameFlag == null) {
            oriNameFlag = false;
        }
        subModule = LogicUtils.or(subModule, FrameworkConst.Str.DEFAULT);
        try {
            switch (sysRole) {
                case ADMIN:
                case AGENT:
                    if (module == null) {
                        module = springApplicationName;
                    }
                    break;
                case USER:
                case ANONYMOUS:
                    oriNameFlag = false;
                    module = springApplicationName;
                    break;
            }
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String fileName = sysRole + "/" + module + "/" + subModule + "/" +
                    (oriNameFlag ? originalFilename : (IdUtil.simpleUUID() + "." + getFileExtension(originalFilename)));
//            minioClient.putObject(
//                    PutObjectArgs.builder()
//                            .bucket(bucket)
//                            .object(fileName)
//                            .stream(inputStream, file.getSize(), -1)
//                            .contentType(file.getContentType())
//                            .build()
//            );
            MinioUploadHttpUtil.uploadFile(
                    minioProperties.getEndpoint(),
                    minioProperties.getBucket(),// 项目编号
                    fileName,
                    inputStream,
                    file.getSize(),
                    minioProperties.getAccessKey(),
                    minioProperties.getSecretKey()
            );
            return "{host}/" + bucket + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("Upload failed", e);
        }
    }

    public static String getFileExtension(String fileName) {
        Path path = Paths.get(fileName);
        String extension = null;
        if (path.getFileName() != null) {
            String fileNameString = path.getFileName().toString();
            int i = fileNameString.lastIndexOf('.');
            if (i > 0 && i < fileNameString.length() - 1) {
                extension = fileNameString.substring(i + 1).toLowerCase();
            }
        }
        return extension;
    }
}
